const Parse = require('parse/node')

Parse.Cloud.define('updateGoodSpecStock', (req, res) => {
  let specs = req.params.data
  const GoodsSpecification = Parse.Object.extend('GoodsSpecification')
  const getObjects = (dir = +1) => {
    let objects = []
    for (var i = 0; i < specs.length; i++) {
      let v = specs[i]
      if (v.stock) {
        var obj = GoodsSpecification.createWithoutData(v.id)
        obj.set('stock', dir * -v.stock)
        obj.increment('sellVolumn', dir * v.stock)
        objects.push(obj)
      }
    }
    return objects
  }
  Parse.Object.saveAll(getObjects()).then(data => res.success(data))
    .catch(() => {
      res.error('库存不足')
      Parse.Object.saveAll(getObjects(-1))
    })
})
